package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.PersonalScoreList.PersonalScoreContent;
import com.isunland.managesystem.entity.PersonalUseableScore;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

/**
 * Created by wu on 2016/4/21.
 * 个人奖惩积分详情
 */
public class PersonalScoreDetailFragment extends BaseFragment {

  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.PersonalScoreDetailFragment.EXTRA_VALUE";
  /* 区分来自积分填报*/
  public static final String EXTRA_FROM =
      "com.isunland.managesystem.ui.PersonalScoreDetailFragment.EXTRA_FROM";
  /* 区分是个人积分  还是分派积分  */
  public static final String EXTRA_TYPE =
      "com.isunland.managesystem.ui.PersonalScoreDetailFragment.EXTRA_TYPE";
  protected static final String PERSONAL = "personal";//所得积分
  protected static final String ASSIGN = "assign";//所派积分
  protected static final String FILL = "fill";//来自积分填报
  protected static final String APPROVAL = "APPROVAL";//来自积分审批

  private TextView mTv_registerTime;//奖惩职员
  private TextView mTv_payPerson;//奖惩职员
  private TextView mTv_inPerson;//被奖惩职员
  private TextView mTv_staffDepartment;//所在人事部门
  private TextView mTv_positionName;//岗位
  private TextView mTv_scoreType;//奖惩类别
  private TextView mTv_scoreContent;//奖惩内容
  private TextView mTv_scoresAdd;//奖励积分
  private TextView mTv_scoresPlus;//扣减积分

  private PersonalScoreContent mContent;
  private String type = "";
  private String from = "";
  private String remindMsg;

  private LinearLayout llHeader;
  private TextView tvContent1;
  private TextView tvTitle1;
  private TextView tvContent2;
  private TextView tvTitle2;
  private TextView tvContent3;
  private TextView tvTitle3;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);

    mContent = (PersonalScoreContent) getArguments().getSerializable(EXTRA_VALUE);
    type = (String) getArguments().getSerializable(EXTRA_TYPE);
    from = getArguments().getString(EXTRA_FROM);
    if (type.equals(PERSONAL)) {
      setTitleCustom(R.string.personalScoreDetail);
    } else if (type.equals(ASSIGN)) {
      setTitleCustom(R.string.assignScoreDetail);
    }
    //积分审批
    if (APPROVAL.equalsIgnoreCase(from)) {
      VolleyPostGetScore();
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    if (FILL.equalsIgnoreCase(from)) {
      inflater.inflate(R.menu.menu_reback_msg, menu);
      if (!DataStatus.SUBMIT.equalsIgnoreCase(mContent.getDataStatus())) {
        //提交状态才显示撤销
        menu.getItem(0).setVisible(false);
      }
    }
    //积分审批
    if (APPROVAL.equalsIgnoreCase(from)) {
      inflater.inflate(R.menu.menu_pass_stop_score, menu);
      if (DataStatus.SUBMIT.equalsIgnoreCase(mContent.getDataStatus())) {
        //提交状态: 审核通过和退回
      }
      if (DataStatus.PUBLIS.equalsIgnoreCase(mContent.getDataStatus())) {
        //审核通过: 退回
        menu.getItem(0).setVisible(false);
      }
      if (DataStatus.NEWBACK.equalsIgnoreCase(mContent.getDataStatus())) {
        //退回: 审核通过
        menu.getItem(1).setVisible(false);
      }
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_personal_score_detail_new, container, false);
    findViw(view);
    bindData();
    return view;
  }

  private void findViw(View view) {
    mTv_registerTime = (TextView) view.findViewById(R.id.tv_registerTimeScore);
    mTv_payPerson = (TextView) view.findViewById(R.id.tv_payPerson);
    mTv_inPerson = (TextView) view.findViewById(R.id.tv_inPerson);
    mTv_staffDepartment = (TextView) view.findViewById(R.id.tv_staffDepartment);
    mTv_positionName = (TextView) view.findViewById(R.id.tv_positionName);
    mTv_scoreType = (TextView) view.findViewById(R.id.tv_scoreType);
    mTv_scoreContent = (TextView) view.findViewById(R.id.tv_scoreContent);
    mTv_scoresAdd = (TextView) view.findViewById(R.id.tv_scoresAdd);
    mTv_scoresPlus = (TextView) view.findViewById(R.id.tv_scoresPlus);

    llHeader = (LinearLayout) view.findViewById(R.id.ll_header);
    tvTitle1 = (TextView) view.findViewById(R.id.tv_title1);
    tvContent1 = (TextView) view.findViewById(R.id.tv_content1);
    tvTitle2 = (TextView) view.findViewById(R.id.tv_title2);
    tvContent2 = (TextView) view.findViewById(R.id.tv_content2);
    tvTitle3 = (TextView) view.findViewById(R.id.tv_title3);
    tvContent3 = (TextView) view.findViewById(R.id.tv_content3);
    if (APPROVAL.equalsIgnoreCase(from)) {
      //来自积分审批: 奖惩人已派分值

      llHeader.setVisibility(View.VISIBLE);
      tvContent3.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
      tvContent3.getPaint().setAntiAlias(true);//抗锯齿
      tvContent3.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
          Intent intent = new Intent(getActivity(), ScoreMonthListActivity.class);
          intent.putExtra(ScoreMonthListFragment.EXTRA_PAYID, mContent.getPayStaffId());
          startActivity(intent);
        }
      });
    }
  }

  private void bindData() {
    //个人--奖惩人
    if (type.equals(PERSONAL)) {
      mTv_payPerson.setText(mContent.getPayStaffName());
      mTv_inPerson.setText(mContent.getInStaffName());
      mTv_staffDepartment.setText(mContent.getPayOrgName());
    }
    //分派--被奖惩人
    else if (type.equals(ASSIGN)) {
      mTv_payPerson.setText(mContent.getPayStaffName());
      mTv_inPerson.setText(mContent.getInStaffName());
      mTv_staffDepartment.setText(mContent.getInOrgName());
    }

    mTv_registerTime.setText(mContent.getRegDate());
    mTv_positionName.setText(mContent.getKeypositionName());
    mTv_scoreType.setText(mContent.getRewardKindName());
    mTv_scoreContent.setText(
        MyStringUtil.connect("\u3000\u3000", mContent.getRemark(), "\u3000\u3000",
            mContent.getRewardCom()));
    mTv_scoresAdd.setText(
        getContext().getString(R.string.scoresAddNew, mContent.getRewValue()));//加分
    mTv_scoresPlus.setText(
        getContext().getString(R.string.scoresPlusNew, mContent.getPunValue()));// 减分
  }

  /**
   * 获取所剩余可派奖励分、剩余可派惩罚分
   */
  protected void VolleyPostGetScore() {
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mContent.getMemberCode());
    params.put("staffId", mContent.getPayStaffId());
    params.put("dataStatus", "publish");
    params.put("currentYearMonth", MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE4));
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_GET_ALL_SCORE);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        PersonalUseableScore useableScore = new Gson().fromJson(arg0, PersonalUseableScore.class);
        if (useableScore != null) {
          String mUsabeAddScore = useableScore.getCurrentRewvalue();//可派奖励分
          String mUsablePlusScore = useableScore.getCurrentPunvalue();//可派惩罚分
          String mCownyearSumvalue = useableScore.getCownyearSumvalue();//本月已派分值
          tvContent1.setText(mUsabeAddScore);
          tvContent2.setText(mUsablePlusScore);
          tvContent3.setText(mCownyearSumvalue);
          tvTitle3.setText(MyStringUtil.connect(mContent.getPayStaffName(), "本月已派分"));
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    });
  }

  public static Fragment newInstance(PersonalScoreContent content, String type, String from) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, content);
    bundle.putSerializable(EXTRA_TYPE, type);
    bundle.putString(EXTRA_FROM, from);
    PersonalScoreDetailFragment fragment = new PersonalScoreDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:
        getActivity().finish();
        break;
      case R.id.menu_item_reback:
        //撤销
        volleyPostChange(DataStatus.NEW);
        break;
      case R.id.menu_item_pass:
        //审核通过
        showDialog(BaseEditDialogFragment.newInstance("", R.string.approveTitle)
            .setCallBack(new BaseEditDialogFragment.CallBack() {
              @Override public void select(String message) {
                remindMsg = message;
                volleyPostChange(DataStatus.PUBLIS);
              }
            }));

        break;
      case R.id.menu_item_back:
        //退回修改,需填写退回意见
        showDialog(BaseEditDialogFragment.newInstance("", R.string.backTitle)
            .setCallBack(new BaseEditDialogFragment.CallBack() {
              @Override public void select(String message) {
                remindMsg = message;
                volleyPostChange(DataStatus.NEWBACK);
              }
            }));

        break;

      case R.id.menu_item_msg:
        //审批意见
        mBaseParams.setId(mContent.getId());
        BaseVolleyActivity.newInstance(this, ScoreMsgListActivity.class, mBaseParams, 0);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 撤销
   */
  private void volleyPostChange(String dataStatus) {
    ParamsNotEmpty params = new ParamsNotEmpty();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SCORE_SUBMIT);
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("ids", "'" + mContent.getId() + "'");
    params.put("dataStatus", dataStatus);
    if (DataStatus.NEWBACK.equalsIgnoreCase(dataStatus) || DataStatus.PUBLIS.equalsIgnoreCase(
        dataStatus)) {
      //审核通过和退回修改需填意见
      params.put("msg", remindMsg);//退回意见
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.submit_failure);
      }
    });
  }
}
